package com.settlement.system.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.enums.MemberEnum;
import com.settlement.system.model.entity.SysLazyToolUser;
import com.settlement.system.model.query.SysLazyToolUserQuery;
import com.settlement.system.service.SysLazyToolUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class JobUtils {

    // 日志
    private static final Logger logger = LoggerFactory.getLogger(JobUtils.class);


    private final SysLazyToolUserService sysLazyToolUserService;

    @Scheduled(cron = "0 0 1 * * ?")
    public void checkExpireUser() {
        LocalDate today = LocalDate.now();
        // 检查过期用户
        SysLazyToolUserQuery query = new SysLazyToolUserQuery();
        query.setPageSize(200);
        query.setMember(MemberEnum.Y.getValue());
        Page<SysLazyToolUser> page = sysLazyToolUserService.getPage(query);
        List<SysLazyToolUser> updateList = new ArrayList<>();
        while (page.getRecords().size() > 0) {
            for (SysLazyToolUser sysLazyToolUser : page.getRecords()) {
                if (sysLazyToolUser.getMemberExpireDate() != null && sysLazyToolUser.getMemberExpireDate().isBefore(today)) {
                    // 已过期
                    sysLazyToolUser.setMember(MemberEnum.N.getValue());
                    updateList.add(sysLazyToolUser);
                }
            }
            query.setPageNum(query.getPageNum() + 1);
            page = sysLazyToolUserService.getPage(query);
        }
        if (updateList.size() > 0) {
            sysLazyToolUserService.updateBatchById(updateList);
        }
    }
}
